<template>
  <div>
    <!-- 悬浮客服按钮 -->
    <div
      class="floating-button"
      @click="toggleChat"
      style="
        position: fixed;
        bottom: 20px;
        right: 20px;
        width: 60px;
        height: 60px;
        background-color: #1890ff;
        border-radius: 50%;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        cursor: pointer;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        z-index: 1001;
      "
    >
      💬
    </div>

    <!-- 悬浮聊天窗口 -->
    <div
      v-if="isOpen"
      class="chat-overlay"
      @click="closeChat"
      style="
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0,0,0,0.3);
        z-index: 1000;
      "
    ></div>

    <div
      v-if="isOpen"
      class="chat-window"
      style="
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 400px;
        height: 700px;
        background: white;
        border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        z-index: 1002;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      "
    >
      <!-- 头部 -->
      <div style="padding: 16px; background: #f0f0f0; border-bottom: 1px solid #ddd;
       font-weight: bold; text-align: center; position: relative; color: #363636;">
        🤖 客服机器人
        <button
          @click="closeChat"
          style="
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            background-color: #ff5f47;
          "
        >✕</button>
      </div>

      <!-- 消息区域 -->
      <div
        ref="messagesContainer"
        style="
          flex: 1;
          padding: 16px;
          overflow-y: auto;
          background: #fafafa;
          display: flex;
          flex-direction: column;
        "
      >
        <div
          v-for="(msg, idx) in messages"
          :key="idx"
          style="
            margin-bottom: 12px;
            padding: 8px 12px;
            border-radius: 18px;
            max-width: 70%;
            word-wrap: break-word;
            text-align: left;
          "
          :style="msg.isBot ? 
          {'background': '#e6f7ff', 'align-self': 'flex-start', 'margin-right': 'auto', 'color': '#1890ff'} : 
          {'background': '#fff', 'align-self': 'flex-end', 'margin-left': 'auto', 'border': '1px solid #363636', 'color':'#363636'}"
        >
          {{ msg.text }}
        </div>
      </div>

      <!-- 输入区域 -->
      <div style="padding: 12px; border-top: 1px solid #ddd; display: flex; gap: 8px;">
        <input
          v-model="inputMessage"
          @keyup.enter="sendMessage"
          placeholder="输入您的问题..."
          style="
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
          "
        />
        <button
          @click="sendMessage"
          style="
            padding: 8px 16px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
          "
        >发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import axios from 'axios'
import { getApiUrl, API_CONFIG } from '../config.js'

// 响应式数据
const isOpen = ref(false)
const messages = ref([])
const inputMessage = ref('') 
const sessionId = ref('user_' + Math.random().toString(36).substr(2, 9)) // 简单唯一ID

const messagesContainer = ref(null)

// 打开&关闭聊天窗口
const toggleChat = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    // 打开聊天窗口时，初始化会话
    initializeChat()
  }
}
const closeChat = () => { isOpen.value = false }

// 发送用户输入
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  const userText = inputMessage.value.trim()
  inputMessage.value = ''

  // 添加用户消息
  messages.value.push({ text: userText, isBot: false })

  await fetchBotReply(userText)
}


// 请求机器人回复
const fetchBotReply = async (userText) => {
  try {
    const res = await axios.post(getApiUrl('/bot/api/chat/'), {
      session_id: sessionId.value,
      message: userText
    })

    const data = res.data
    messages.value.push({ text: data.output, isBot: true })

    // 检查是否结束
    if (data.is_ending) {
      options.value = []
      messages.value.push({ text: '对话已结束，感谢您的使用！', isBot: true })
    }

    scrollToBottom()
  } catch (err) {
    console.error('机器人请求失败:', err)
    messages.value.push({ text: '抱歉，机器人暂时无法响应，请稍后再试。', isBot: true })
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 新增：初始化聊天会话
const initializeChat = async () => {
  try {
    const res = await axios.post(getApiUrl('/bot/api/chat/'), {
      session_id: sessionId.value,
      message: "init"  // 可以用任意标识，后端会根据 session_id 返回 greet 的内容
    })

    const data = res.data
    messages.value.push({ text: data.output, isBot: true })
    scrollToBottom()
  } catch (err) {
    console.error('初始化聊天失败:', err)
    messages.value.push({ text: '抱歉，客服系统暂未就绪，请稍后再试。', isBot: true })
  }
}


</script>

<style scoped>
.floating-button:hover {
  background-color: #40a9ff;
}
.chat-window {
  font-family: Arial, sans-serif;
}
</style>